import { useEffect, useState } from 'react';
import { Upload, ModalProps, message } from 'antd';
import { StyledUploadBox } from './styles';
import Modals from '@/components/modals/Modals';
import { SvgIcon } from '@/components/icon';

const { Dragger } = Upload;

interface Props extends ModalProps {
  open?: boolean;
  onCancel?: () => void;
  onFileOk?: (file: File) => void;
}

const UploadModal = ({ open = true, onCancel, onFileOk, ...props }: Props) => {
  const [file, setFile] = useState<File>();
  const [messageApi, contextHolder] = message.useMessage();
  const handleUpload = (files: File) => {
    if (!files.name.endsWith('.xlsx')) {
      messageApi.error('文件格式不正确,只支持xlsx文件');
      return;
    }

    if (files?.size && files.size > 15 * 1024 * 1024) {
      messageApi.error('文件大小不能超过15M');
      return;
    }
    setFile(files);
    return false;
  };

  const handleRemove = () => {
    setFile(undefined);
  };

  const handleOk = () => {
    if (!file) {
      messageApi.error('请选择要导入的名单文件');
      return;
    }

    onFileOk && onFileOk(file);
  };

  const handleClose = () => {
    setFile(undefined);
  };

  return (
    <Modals
      {...props}
      title={'导入名单'}
      open={open}
      onCancel={onCancel}
      onOk={handleOk}
      afterClose={handleClose}
    >
      {contextHolder}
      <ul className="mb-6 list-disc pl-5 text-sm text-[#474C5F]">
        <li>
          根据 xlsx 模板整理要导入的名单。
          <a className="!text-@brand-color !underline" href="/api/openapi/v2/proxy/download">
            下载知识库类型模板
          </a>
        </li>
        <li>只支持 xlsx 文件。</li>
        <li>只支持上传一个文件，单个文件不超过 15MB。</li>
      </ul>
      {file ? (
        <div className="flex h-[110px] items-center justify-between rounded-[16px] bg-[#ECEFF8] py-[16px] pl-[30px] pr-[11px]">
          <div>{file.name}</div>
          <a className="!text-@error-color" onClick={handleRemove}>
            删除
          </a>
        </div>
      ) : (
        <StyledUploadBox>
          <Dragger maxCount={1} beforeUpload={handleUpload} accept={'.xlsx'}>
            <div className="flex h-[78px] flex-col items-center justify-center">
              <SvgIcon icon="icon-upload" size={32} />
              <div className="mt-1 text-center text-[#474C5F]">上传XLSX文件</div>
            </div>
          </Dragger>
        </StyledUploadBox>
      )}
    </Modals>
  );
};

export default UploadModal;
